<?php
/**
 * 会员登陆
 */
namespace Member\Controller;
use \Think\Verify;
use \Org\Yike\Mailer;
use \Org\LoginSdk\ThinkOauth;
class LoginController extends CommonController {
    private $imgObj = '';
    private $_mod = '';
    public function _initialize(){
        parent::_initialize();
        $config = array('imageH'=>50,'imageW'=>150,'length'=>4,'fontSize'=>21);
        $this->imgObj = new Verify($config);
        $this->_mod = D("User");

    }
	
    public function index(){

        if($user){
          redirect(U('Index/index'));
        }

        if(IS_POST){
            $username = I('post.username','');
            $password = I('post.password','');

            if(empty($username) || empty($password)){
                $this->error('请填写用户名或密码');
            }
            $map['username|email|mobile'] = array('eq',$username);
            $info = $this->_mod->where($map)->find();
            if(!$info){
                $this->error('会员不存在');
            }else{
                if(_md5($password) !== $info['password']){
                    $this->error('密码不正确');
                }
                if($info['status']==0){
                    $this->error('账号审核中');
                }
                //设置session过期时间
                session(array('name'=>'userInfo','expire'=>10));
                $session['id'] = $info['id'];
                $session['username'] = $info['username'];
                $session['email']    = $info['email'];
                session('userInfo',$session);
                $member['login_time'] = time();
                $member['login_ip']   = get_client_ip();
                D("UserInfo")->where(array('user_id'=>$info['id']))->save($member);
                D("UserInfo")->where(array('user_id'=>$info['id']))->setInc('login_num');

                if(C('LOGIN_POINT')>0){
                    if(!D("UserRecord")->where(array('user_id'=>$info['id'],'type'=>1,'option_date'=>date("Y-m-d")))->find()){
                        $record['num'] = C('LOGIN_POINT');
                        $record['memo'] = '会员登录';
                        $record['title'] = '会员当天首次登录赠送积分：'.C('LOGIN_POINT');
                        Record($member['user_id'],$record);
                    }
                }
                header("Location:".U('Index/index'));
            }

        }
        $this->assign ('filename', createQR('WQ你好','kkk.png'));
        $this->display();
    }

    public function login($type=null){
        if($type){
            $sns = ThinkOauth::getInstance($type);
            redirect($sns->getRequestCodeURL());
        }else{
            $this->redirect('index');
        }
    }

    public function callback($type = null, $code = null) {
        unset($_COOKIE);
        header("Content-type: text/html; charset=utf-8");
        (empty($type) || empty($code)) && $this->error('参数错误');
        $sns = ThinkOauth::getInstance($type);

        //腾讯微博需传递的额外参数
        $extend = null;
        if ($type == 'tencent') {
            $extend = array('openid' => I('get.openid'), 'openkey' => I('get.openkey'));
        }
        $tokenArr = $sns->getAccessToken($code, $extend);
        $openid = trim($tokenArr['openid']);
        $token = trim($tokenArr['access_token']);
        cookie("openid", $openid);
        cookie("access_token", $token);

        if ($openid) {
            $field = strtolower($type);
            cookie("field", $field);
            $data[$field] = $openid;
            $binding = M('user_binding')->where($data)->find();
            if ($binding) { //若是有该账号就登录
                $info = $this->_mod->where(array('id'=>$binding['user_id']))->field('id,username,email')->find();
                $session['id'] = $info['id'];
                $session['username'] = $info['username'];
                $session['email']    = $info['email'];
                session('userInfo',$session);
                $member['login_time'] = time();
                $member['login_ip']   = get_client_ip();
                D("UserInfo")->where(array('user_id'=>$info['id']))->save($member);
                D("UserInfo")->where(array('user_id'=>$info['id']))->setInc('login_num');

                if(C('LOGIN_POINT')>0){
                    if(!D("UserRecord")->where(array('user_id'=>$info['id'],'type'=>1,'option_date'=>date("Y-m-d")))->find()){
                        $record['num'] = C('LOGIN_POINT');
                        $record['memo'] = '会员登录';
                        $record['title'] = '会员当天首次登录赠送积分：'.C('LOGIN_POINT');
                        Record($member['user_id'],$record);
                    }
                }
                $this->success('登陆成功',U('Index/index'));
            } else { //没有的话绑定
                $user = session('userInfo');
                $user_id = $user['id'];
                $username = $user['username'];
                if ($user_id && $username) { //用户已登录，自动绑定
                    $user_binding = M('user_binding')->where(array('user_id'=>$user_id))->find();
                    if($user_binding){
                        $res = M('user_binding')->where(array('user_id'=>$user_id))->save(array($field => $openid));
                    }else{
                        $res = M('user_binding')->add(array($field => $openid,'user_id'=>$user_id));
                    }
                    //绑定账号
                    if($res){
                        $this->success("绑定成功！", U('Index/index'));
                    }else{
                        $this->error("绑定失败！", U('Index/index'));
                    }
                } else { //用户未登录，跳转到绑定页面
                    if ($field == 'qq') { //针对新版qq互联在绑定页，要显示昵称，否则不通过***
                        $data = $sns->call('user/get_user_info');
                        $nickname = $data['nickname'];
                    } else {
                        $userinfo = $sns->$type($tokenArr);//A('Type', 'Event')->$type($tokenArr);
                        $nickname = $userinfo['name'];
                    }
                    cookie('nickname', $nickname);
                    $this->redirect("Login/bind");
                }
            }
        } else {
           $this->error('系统出错，请稍后再试！',U('Login/index'));
        }
    }

    public function bind() {
        $nickname = cookie('nickname');
        $assignArr = array(
            "title" => "绑定账号",
            "nickname" => $nickname
        );
        if(IS_POST){
            $verify_code = I('post.verfiy');
            if(!$this->checkverfiy($verify_code)){
                $this->error('验证码不正确');
            }
            $username = I('post.username','');
            $password = I('post.password','');
            if(empty($username) || empty($password)){
                $this->error('请填写用户名或密码');
            }
            $map['username|email'] = $username;
            $info = $this->_mod->where($map)->find();
            $field = cookie('field');
            $openid =  cookie("openid");
            $data[$field] = $openid;
            if($info){//绑定账号
                if($info['password'] == _md5($password)){
                    $session = array(
                        'id' => $info['id'],
                        'username' => $info['username'],
                        'email'    => $info['email']
                    );
                    session('userInfo',$session);
                    $member['login_time'] = time();
                    $member['login_ip']   = get_client_ip();
                    D("UserInfo")->where(array('user_id'=>$info['id']))->save($member);
                    D("UserInfo")->where(array('user_id'=>$info['id']))->setInc('login_num');

                    if(C('LOGIN_POINT')>0){
                        if(!D("UserRecord")->where(array('user_id'=>$info['id'],'type'=>1,'option_date'=>date("Y-m-d")))->find()){
                            $record['num'] = C('LOGIN_POINT');
                            $record['memo'] = '会员登录';
                            $record['title'] = '会员当天首次登录赠送积分：'.C('LOGIN_POINT');
                            Record($member['user_id'],$record);
                        }
                    }
                    $user_binding = M('user_binding')->where(array('used_id'=>$info['id']))->find();
                    if($user_binding){
                         M('user_binding')->where(array('user_id'=>$info['id']))->save(array($field => $openid));
                    }else{
                        M('user_binding')->add(array($field => $openid,'user_id'=>$info['id']));
                    }
                    $this->redirect("Index/index");
                }else{
                    $this->error('密码不正确');
                }

            }
        }
        $this->assign($assignArr);
        $this->display();
    }

    public function reg(){
        if(IS_POST){
            if(C('ALLOW_REGSITER')==0){
                $this->error('注册通道被关闭');
            }

            $verify_code = I('post.captcha_code');
            if(!$this->checkverfiy($verify_code)){
                $this->error('验证码不正确');
            }

            $data['username']  = I('post.username','');
            $password          = I('post.password','');
            $data['password']  = _md5($password);
            $data['email']     = I('post.email','');
            $data['mobile']    = I('post.mobile','');
            //推荐码
            do {
                $code = codestr(6);
                $base_data = M ('user')->where ('recomm="'.$code.'"')->getField ('id');
            } while (!empty ($base_data));
            $data['recomm'] = $code;

            if($this->_mod->where(array('email'=>$data['email']))->count()){
                $this->error('邮箱号码已经存在');
           }
            if($this->_mod->where(array('mobile'=>$data['mobile']))->count()){
                $this->error('手机号码已经存在');
            }
            if($this->_mod->where(array('username'=>$data['username']))->count()){
                $this->error('用户名已经存在');
            }
            if(empty($data['username']) || empty($password)){
                $this->error('请填写完整后再提交');
            }

            //如果是中介会员需要审核
            $cate_id = intval($_POST['cate_id']) ? $_POST['cate_id'] : 1;
            if ($cate_id <= 2) $data['status'] = 0;

            //新增注册用户
            $this->_mod ->create($data);
            if($this->_mod->add()){
                $id = $this->_mod->getLastInsID();
                //如有填推荐人
                $be_recomm = I('post.be_recomm','');
                if (!empty ($be_recomm) && (strlen($be_recomm)>=6)){
                    $user_info = M ('user')->field ('id,be_recomm')->where ('recomm="'.$be_recomm.'"')->find();
                    $ids = $user_info['be_recomm'].$id.',';
                    M ('user')->where ('id="'.$user_info['id'])->setField('be_recomm', $ids);
                }
                $member['user_id'] = $id;
                $member['login_time'] = $member['reg_time'] = time();
                $member['login_num'] = 1;
                $member['cate_id'] = $cate_id;
                $member['login_ip'] = $member['reg_ip'] = get_client_ip();
                //生成二维码图
                $QRcenter = 'http://'._SITE.'/user.php?m=Member&c=Login&a=reg&recomm='.$code;
                $path = $code.'.png';
                $member['website'] = createQR($QRcenter, $path, 5);

                //保存用户详细信息
                D("UserInfo")->add($member);

                $session = array(
                    'id' => $member['user_id'],
                    'username' => $data['username'],
                    'email'    => $data['email']
                );
                session('userInfo',$session);
                $account['user_id'] = $member['user_id'];

                if(D("UserAccount")->add($account)){
                    if(C('REGSITER_POINT')>0){
                        $record['num'] = C('REGSITER_POINT');
                        $record['memo'] = '会员注册';
                        $record['title'] = '会员注册赠送积分：'.C('REGSITER_POINT');
                        Record($member['user_id'],$record);
                    }
                    if(C('REGSITER_MONEY')>0){
                        $record['num'] = C('REGSITER_MONEY');
                        $record['memo'] = '会员注册';
                        $record['title'] = '会员注册赠送金额：'.C('REGSITER_MONEY');
                        Record($member['user_id'],$record,2);
                    }
                }
                $this->success('注册成功,正为您转向会员中心',U('Index/index'));
            }
        }else{
            $this->user_cate = M('user_cate')->where(array('status'=>1))->order('ordid desc')->select();
            $be_recomm = I ('get.code', '');
            $this->assign ('be_recomm', $be_recomm);
            $this->display();
        }
    }

    //找回密码
    public function pass(){
        if(IS_POST){
            $verify_code = I('post.captcha_code');
            if(!$this->checkverfiy($verify_code)){
                $this->error('验证码不正确');
            }
            $type = I('post.type','');
            $mobile = $email = $val = I('post.val','');
            if($type=='phone'){
                if(!$val && !is_numeric($val)){
                    $this->error('不是要效的手机号码!');
                }
                $map['mobile'] = array('eq',$mobile);
                $info = $this->_mod->where($map)->find();
                if(!$info){
                    $this->error('输入的手机号码找不到对应的账号');
                }else{
                    $this->info = $info;
                    $this->display('phone_pass2');
                }
            }else{
                if(!$val &&  !strpos($val,'@')){
                    $this->error('邮箱不能为空!');
                }
                $map['email'] = array('eq',$email);
                $info = $this->_mod->where($map)->find();
                if(!$info){
                    $this->error('输入的邮箱找不到对应的账号');
                }else{
                    $this->info = $info;
                    $this->display('email_pass2');
                }

            }
        }else{
            $this->display();
        }
    }

    //手机验证码核对
    public function phonePass(){
        $mobile = I('post.mobile','');
        $map['mobile'] = array('eq',$mobile);
        $info = $this->_mod->where($map)->find();
        if(!$info['mobile']){
            $this->error('找不对对应的账号信息');
        }
        $code = session('password_code');
        if($code['mobile'] != $info['mobile'] or ($code['time']+3600)<time()){
            $this->error('手机短信验证信息超时');
        }
        if($code['code'] != I('post.code','')){
            $this->error('手机短信验证输入信息不对应');
        }
        $this->info = $info;
        $this->display('phone_edit');
    }
    //邮箱验证码核对
    public function emailPass(){
        $email = I('post.email','');
        $map['email'] = array('eq',$email);
        $info = $this->_mod->where($map)->find();
        if(!$info['email']){
            $this->error('找不对对应的账号信息');
        }
        $code = session('password_code');
        if($code['email'] != $info['email'] or ($code['time']+3600)<time()){
            $this->error('邮箱验证信息超时');
        }
        if($code['code'] != I('post.code','')){
            $this->error('邮箱验证输入信息不对应');
        }
        $this->info = $info;
        $this->display('email_edit');
    }

    //重置密码
    public function passEdit(){
        if(IS_POST){
            $password    = I('post.password','');
            $repassword    = I('post.repassword','');
            if($password=='' or $password!=$repassword){
                $this->error('两次密码输入不一样');
            }
            $info = M("User")->where(array('id'=>intval($_POST['id'])))->find();
            $session = session('password_code');
            if(($info['mobile'] && $session['mobile']==$info['mobile']) or ($info['email'] && $session['email']==$info['email'])){
                $res = M("User")->where(array('id'=>$info['id']))->save(array('password'=>_md5($password)));
                if($res){
                    session('password_code',null);
                    $this->success('密码修改成功',U('Login/index'));
                }else{
                    $this->error('密码修改失败');
                }
            }else{
                $this->error('找不到对应的会员信息');
            }
        }
    }

    public function checkName(){
        $username = I('post.username','');
        $email    = I('post.email','');
        $mobile    = I('post.mobile','');
        if($username){
            $map['username'] = array('eq',$username);
        }
        if($email){
            $map['email'] = array('eq',$email);
        }
        if($mobile){
            $map['mobile'] = array('eq',$mobile);
        }
        $info = M("User")->where($map)->find();
        if($info){
            $this->ajaxReturn(array('status'=>0));
        }else{
            $this->ajaxReturn(array('status'=>1));
        }
    }

    public function checkCode(){
        $code = I('post.code','');
        $info = $this->checkverfiy($code);
        if($info){
            $this->ajaxReturn(array('status'=>1));
        }else{
            $this->ajaxReturn(array('status'=>0));
        }
    }

    //获取手机认证码
    public function getMobileCode(){
        $mobile = I('post.mobile','');
        $map['mobile'] = array('eq',$mobile);
        $info = $this->_mod->where($map)->find();
        if(!$info['mobile']){
            $this->ajaxReturn(array('status'=>0,'msg'=>'找不到对应的会员信息'));
        }else{
            $session = session('password_code');
            if((!$session['time'] or ($session['time']+3600)<time()) && $info['mobile'] != $session['mobile']){
                $code = rand(111111,888888);
                $tpl = smsTpl('pass_tpl',$data=array('code'=>$code,'phone'=>$info['mobile'],'username'=>$info['username'],'sitename'=>$this->siteName));
                $smsRes = sendSMS($info['mobile'],$tpl);
                if($smsRes==100){
                    session('password_code',array(
                                'code'=>$code,
                                'mobile'=>$info['mobile'],
                                'email'=>$info['email'],
                                'time'=>time())
                            );
                    $this->ajaxReturn(array('status'=>1,'msg'=>'短信发送成功!'));
                }else{
                    $this->ajaxReturn(array('status'=>0,'msg'=>'短信发送失败!'));
                }
            }else{
                $this->ajaxReturn(array('status'=>0,'msg'=>'短信已经发送,请查看你的手机!'));
            }
        }
    }

    //获取邮箱认证码
    public function getEmailCode(){
        $email = I('post.email','');
        $map['email'] = array('eq',$email);
        $info = $this->_mod->where($map)->find();
        if(!$info['email']){
            $this->ajaxReturn(array('status'=>0,'msg'=>'找不到对应的会员信息'));
        }else{
            $session = session('password_code');
            if((!$session['time'] or ($session['time']+3600)<time()) && $info['email'] != $session['email']){
                $code = rand(111111,888888);
                $tpl = smsTpl('pass_tpl',$data=array('code'=>$code,'phone'=>$info['mobile'],'username'=>$info['username'],'sitename'=>$this->siteName));
                $mail = new Mailer(_setting('email',1));
                $title = $this->siteName.'找回会员密码认证码';
                if( $mail->send_email($title,$tpl,$email)){
                    session('password_code',array(
                            'code'=>$code,
                            'mobile'=>$info['mobile'],
                            'email'=>$info['email'],
                            'time'=>time())
                    );
                    $this->ajaxReturn(array('status'=>1,'msg'=>'邮箱发送成功!'));
                }else{
                    $this->ajaxReturn(array('status'=>0,'msg'=>'邮箱发送失败!'));
                }
            }else{
                $this->ajaxReturn(array('status'=>0,'msg'=>'验证码已经发送,请查看你的邮箱!'));
            }
        }
    }

    public function verfiy(){
        $this->imgObj->entry('userverfiy');
    }

    public function logout(){
        session('userInfo',null);
        $name = d_name();
        setcookie('uid', '', time() - 3600, '/', $name);
        setcookie('fangcms_uid', '', time() - 3600, '/', $name);
        setcookie('fangcms_keys', '', time() - 3600, '/', $name);
        $this->redirect('Login/index');
    }

    public function checkverfiy($code){
        if(!$this->imgObj->check($code,'userverfiy')){
            return false;
        }
        return true;
    }
 
}